package com.example.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.File;
import com.example.entity.UserAction;
import com.example.mapper.UserActionMapper;
import com.example.service.LogService;
import com.example.service.UserActionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-05-31
 */
@RestController
@RequestMapping("//userAction")
public class UserActionController {
    @Resource
    private UserActionService userActionService;
    @Resource
    private LogService logService;
    @Resource
    private HttpServletRequest request;

    @PostMapping
    public Result<?> save(@RequestBody UserAction userAction) {
        logService.log(StrUtil.format("新增行为：{} ", userAction.getUsername()));
        userAction.setActiontime(DateUtil.formatDateTime(new Date()));
        userActionService.update1(userAction.getAction(),userAction.getFilename());
        return Result.success(userActionService.save(userAction));
    }

    @PutMapping
    public Result<?> update(@RequestBody UserAction userAction) {
        logService.log(StrUtil.format("更新行为：{} ", userAction.getUsername()));
        return Result.success(userActionService.updateById(userAction));
    }

    @GetMapping("/{id}")
    public Result<UserAction> findById(@PathVariable String id) {
        return Result.success(userActionService.getById(id));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        UserAction userAction = userActionService.getById(id);
        logService.log(StrUtil.format("删除文件{} ",userAction.getFilename()));
        userActionService.removeById(id);
        return Result.success();
    }
    @GetMapping
    public Result<List<UserAction>> findAll() {
        return Result.success(userActionService.list());
    }
    @GetMapping("/page")
    public Result<IPage<UserAction>> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return Result.success(userActionService.page(new Page<>(pageNum, pageSize), Wrappers.<UserAction>lambdaQuery().like(UserAction::getUsername, name)));
    }

}

